﻿using System;
using System.Threading.Tasks;
using Casamiel.Common;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Options;

namespace Casamiel.API.Infrastructure.Filters
{

    /****
    /// <summary>
    /// Test authorization filter.
    /// </summary>
    public class TestAuthorizationFilter : Attribute, IAsyncActionFilter
    {
        /// <summary>
        /// Ons the action execution async.
        /// </summary>
        /// <returns>The action execution async.</returns>
        /// <param name="context">Context.</param>
        /// <param name="next">Next.</param>
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
#if DEBUG
            Console.WriteLine(context.ActionDescriptor.DisplayName);
            await next().ConfigureAwait(false);
#else
            await next();
            //context.Result = new JsonResult("没有权限");
            //return;
#endif
        }
        
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            if (context.Filters.Any(item => item is IAllowAnonymousFilter))
            {
                return;
            }

            if (!(context.ActionDescriptor is ControllerActionDescriptor))
            {
                return;
            }
            var attributeList = new List<object>();
            attributeList.AddRange((context.ActionDescriptor as ControllerActionDescriptor).MethodInfo.GetCustomAttributes(true));
            attributeList.AddRange((context.ActionDescriptor as ControllerActionDescriptor).MethodInfo.DeclaringType.GetCustomAttributes(true));
            var authorizeAttributes = attributeList.OfType<TestAuthorizeAttribute>().ToList();
            var claims = context.HttpContext.User.Claims;
            // 从claims取出用户相关信息，到数据库中取得用户具备的权限码，与当前Controller或Action标识的权限码做比较
            //var userPermissions = "User_Edit";
            //if (!authorizeAttributes.Any(s => s.Permission.Equals(userPermissions)))
            //{
            //    context.Result = new JsonResult("没有权限");
            //}
            return;
        }
        
        

    }
  
    /// <summary>
    /// Test authorize attribute.
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
    public class TestAuthorizeAttribute : AuthorizeAttribute
    {
        /// <summary>
        /// Gets or sets the permission.
        /// </summary>
        /// <value>The permission.</value>
        public string Permission { get; set; }
        /// <summary>
        /// Initializes a new instance of the <see cref="T:Casamiel.API.Infrastructure.Filters.TestAuthorizeAttribute"/> class.
        /// </summary>
        public TestAuthorizeAttribute
            ()
        {
            Permission = "";
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="T:Casamiel.API.Infrastructure.Filters.TestAuthorizeAttribute"/> class.
        /// </summary>
        /// <param name="permission">Permission.</param>
        public TestAuthorizeAttribute(string permission)
        {
            Permission = permission;
        }

    }
    */
    /// <summary>
    /// Action filter.
    /// </summary>
    public class ActionFilter : IActionFilter
    {
        private readonly CasamielSettings _settings;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="configuration"></param>
        public ActionFilter(IOptionsSnapshot<CasamielSettings> configuration)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            _settings = configuration.Value;
        }
        //  private readonly NLog.ILogger logger = LogManager.GetLogger("BizInfo");
        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public void OnActionExecuted(ActionExecutedContext context)
        {
            //var httpContext = context.HttpContext;
            //var stopwach = httpContext.Items["StopwachKey"] as Stopwatch;
            //stopwach.Stop();

            //var time = stopwach.Elapsed;
            //Console.WriteLine($"{context.ActionDescriptor.DisplayName}执行耗时:{stopwach.ElapsedMilliseconds}毫秒");
            //logger.Trace($"{context.ActionDescriptor.DisplayName}执行耗时:{stopwach.ElapsedMilliseconds.ToString()}毫秒");
            //#if DEBUG
            //            Console.WriteLine($"{context.ActionDescriptor.DisplayName}执行耗时:{stopwach.ElapsedMilliseconds}毫秒");

            //#else
            //            if (stopwach.ElapsedMilliseconds > 80)
            //            {
            //                //Console.WriteLine($"{context.ActionDescriptor.DisplayName}执行耗时:{stopwach.ElapsedMilliseconds}毫秒");
            //                logger.Trace($"ip:{context.HttpContext.Request.GetUserIp()},{context.ActionDescriptor.DisplayName}执行耗时:{stopwach.ElapsedMilliseconds}毫秒");
            //            }
            //#endif

            //var beign =(long) context.HttpContext.Items["StopwachKey"];
            //var end = DatetimeUtil.GetUnixTime(DateTime.Now, TimePrecision.Millisecond);
            //logger.Trace($"ip:{context.HttpContext.Request.GetUserIp()},{context.ActionDescriptor.DisplayName}执行耗时:{end-beign}毫秒");

        }
        /// <summary>
        /// Ons the action executing.
        /// </summary>
        /// <param name="context">Context.</param>
        public void OnActionExecuting(ActionExecutingContext context)
        {
            //if(context.HttpContext.Request.Headers["User-Agent"].ToString().Contains("okhttp/3.3.1")){
            //    //context.Result = new JsonResult("没有权限");
            //    //return;
            //    Console.WriteLine($"{context.HttpContext.Request.Headers["User - Agent"].ToString()},ip:{context.HttpContext.Request.GetUserIp()}");

            //}
            if (!_settings.ApiEnable) {
                string action = ((Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor)context.ActionDescriptor).ControllerName.ToLower();
                if (action != "notify" && action != "appwxpaynotify" && action != "miniapppaynotify") {
                    var c = new ContentResult();
                    c.Content = "";
                    context.Result = c;
                    //context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                    return;
                }
            }
            //var stopwach = new Stopwatch();
            //stopwach.Start();
            //var stopwach = DatetimeUtil.GetUnixTime(DateTime.Now, TimePrecision.Millisecond);
            //context.HttpContext.Items.Add("StopwachKey", stopwach);
        }
    }
}
